package com.shop.cereshop.app.controller.gaode;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.shop.cereshop.app.domain.gaode.GaodePathResponse;
import com.shop.cereshop.app.param.map.OffsetBoundsRequest;
import com.shop.cereshop.app.service.gaode.GaodeMapService;
import com.shop.cereshop.app.service.map.OffsetBoundsService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.map.OffsetBoundsResp;
import com.shop.cereshop.commons.domain.map.PathPlanResp;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.tencent.im.constant.CustomMsgModelType;
import com.shop.cereshop.commons.tencent.im.enums.im.MsgTypeEnum;
import com.shop.cereshop.commons.tencent.im.model.msg.data.CustomMsgData;
import com.shop.cereshop.commons.tencent.im.model.msg.data.CustomMsgDataModel;
import com.shop.cereshop.commons.tencent.im.model.msg.dto.MsgRequestDTO;
import com.shop.cereshop.commons.tencent.im.model.response.SendGroupMsgResponse;
import com.shop.cereshop.commons.tencent.im.model.response.SendMsgResponse;
import com.shop.cereshop.commons.tencent.im.service.TimMsgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * 地图功能模块
 */
@RestController
@RequestMapping("map")
/**
 * 注解方式生成日志对象，指定topic生成对象类名
 */
@Slf4j(topic = "MapController")
@Api(value = "地图模块", tags = "地图模块")
public class MapController {

    @Autowired
    private GaodeMapService gaodeMapService;

    @Autowired
    private OffsetBoundsService offsetBoundsService;

    @Resource
    TimMsgService timMsgService;

    /**
     * 获取骑行路径规划
     *
     * @param origin      起点经纬度 (格式: x,y)
     * @param destination 终点经纬度 (格式: x,y)
     * @return 路径规划结果
     */
    @GetMapping("bicycling")
    @ApiOperation(value = "获取路径规划")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "origin", value = "起点经纬度 (格式: x,y)", required = true, dataType = "String"),
            @ApiImplicitParam(name = "destination", value = "终点经纬度 (格式: x,y)", required = true, dataType = "String"),
            @ApiImplicitParam(name = "types", value = "路径规划类型 1 步行 2 骑行 3 驾车  1,2返回步行与骑行 , 2,3 返回骑行与驾车", required = true, dataType = "String")
    })
    public Result<PathPlanResp> getBicyclingPath(@RequestParam("origin") String origin, @RequestParam("destination") String destination, String types) {
        PathPlanResp data = new PathPlanResp();
        if (types.contains("1")) {
            GaodePathResponse walkingPath = gaodeMapService.getWalkingPath(origin, destination);
            if (StrUtil.equals(walkingPath.getInfo(), "OK")) {
                //时间 秒
                data.setWalkTime(walkingPath.getRoute().getPaths().get(0).getDuration());
                //距离
                data.setWalkDistance(walkingPath.getRoute().getPaths().get(0).getDistance());
            }
        }
        if (types.contains("2")) {
            GaodePathResponse bicyclingPath = gaodeMapService.getBicyclingPath(origin, destination);
            if (0 == bicyclingPath.getErrcode()) {
                //时间 秒
                data.setRideTime(bicyclingPath.getData().getPaths().get(0).getDuration());
                //距离
                data.setRideDistance(bicyclingPath.getData().getPaths().get(0).getDistance());
            }
        }
        if (types.contains("3")) {
            GaodePathResponse drivingPath = gaodeMapService.getDrivingPath(origin, destination);
            if (StrUtil.equals(drivingPath.getInfo(), "OK")) {
                //时间 秒
                data.setDriveTime(drivingPath.getRoute().getPaths().get(0).getDuration());
                //距离
                data.setDriveDistance(drivingPath.getRoute().getPaths().get(0).getDistance());
            }
        }
        return Result.success(data);
    }

    /**
     * 生成以指定点为中心，上下各50米、左右各100米的矩形经纬度串
     * <p>
     * 返回顺序：西北→东北→东南→西南 的四个顶点，格式：lng,lat;lng,lat;...
     */
    @PostMapping("sendLocation")
    @ApiOperation(value = "发送当前点位")
    public Result<OffsetBoundsResp> generateOffsetBounds(
            HttpServletRequest request,
            @Validated @RequestBody OffsetBoundsRequest param) {
        // 从token获取用户对象
        CereBuyerUser user = (CereBuyerUser) request.getAttribute("user");
        if (cn.hutool.core.bean.BeanUtil.isEmpty(user)) {
            return Result.failed(CoReturnFormat.USER_NOT_LOGIN);
        }
        OffsetBoundsResp resp = offsetBoundsService.generateBounds(user, param);
        CustomMsgDataModel customMsgDataModel = new CustomMsgDataModel(CustomMsgModelType.LOCATION, resp);
        CustomMsgData msgData = new CustomMsgData();
        msgData.setDesc("位置信息");
        msgData.setData(JSON.toJSONString(customMsgDataModel));
        MsgRequestDTO requestDTO = new MsgRequestDTO();
        requestDTO.setFromAccount(String.valueOf(user.getBuyerUserId()));
        if (StrUtil.isEmpty(param.getGroupId())) {
            requestDTO.setToAccount(param.getReceiverUserId());
            SendMsgResponse sendMsgResponse = timMsgService.sendC2cMsg(MsgTypeEnum.CUSTOM, msgData, requestDTO);
            if (sendMsgResponse.getActionStatus().equals("OK")) {
                return Result.success();
            }
        } else {
            requestDTO.setGroupId(param.getGroupId());
            SendGroupMsgResponse sendGroupMsgResponse = timMsgService.sendGroupMsg(MsgTypeEnum.CUSTOM, msgData, requestDTO);
            if (sendGroupMsgResponse.getActionStatus().equals("OK")) {
                return Result.success();
            }
        }
        return Result.failed(CoReturnFormat.FAIL);
    }
}
